package com.moxiao.yfjh.module.order.controller.app;

import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.operatelog.core.annotations.OperateLog;
import com.moxiao.yfjh.module.activity.controller.admin.activityEnroll.vo.ActivityEnrollExportReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityInfo.vo.ActivityInfoRespVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityPackage.vo.ActivityPackageExportReqVO;
import com.moxiao.yfjh.module.activity.convert.activityInfo.ActivityInfoConvert;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityEnroll.ActivityEnrollDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityInfo.ActivityInfoDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityPackage.ActivityPackageDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.productInfo.ProductInfoDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.productType.ProductTypeDO;
import com.moxiao.yfjh.module.activity.service.activityEnroll.ActivityEnrollService;
import com.moxiao.yfjh.module.activity.service.activityInfo.ActivityInfoService;
import com.moxiao.yfjh.module.activity.service.activityPackage.ActivityPackageService;
import com.moxiao.yfjh.module.activity.service.activityVerificate.ActivityVerificateService;
import com.moxiao.yfjh.module.activity.service.activityenrollverificate.ActivityEnrollVerificateService;
import com.moxiao.yfjh.module.activity.service.productInfo.ProductInfoService;
import com.moxiao.yfjh.module.activity.service.productType.ProductTypeService;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.order.common.GenNoCommonUtil;
import com.moxiao.yfjh.module.order.controller.admin.blindTradeRefund.vo.BlindTradeRefundCreateReqVO;
import com.moxiao.yfjh.module.order.controller.admin.blindTradeRefund.vo.BlindTradeRefundPageReqVO;
import com.moxiao.yfjh.module.order.controller.admin.blindTradeRefund.vo.BlindTradeRefundRespVO;
import com.moxiao.yfjh.module.order.controller.admin.blindTradeRefund.vo.BlindTradeRefundUpdateReqVO;
import com.moxiao.yfjh.module.order.controller.app.vo.AppRefund;
import com.moxiao.yfjh.module.order.convert.blindTradeRefund.BlindTradeRefundConvert;
import com.moxiao.yfjh.module.order.dal.dataobject.blindTradeRefund.BlindTradeRefundDO;
import com.moxiao.yfjh.module.order.tradeRefund.blindTradeRefund.BlindTradeRefundService;
import com.moxiao.yfjh.module.system.service.dict.DictDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;
import static com.moxiao.yfjh.framework.operatelog.core.enums.OperateTypeEnum.UPDATE;
import static com.moxiao.yfjh.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static com.moxiao.yfjh.module.activity.enums.ErrorCodeConstants.ENROLL_NO_RELATED_ACTIVITIES_FOUND_NOT_EXISTS;

@Tag(name = "App - 相亲订单退款")
@RestController
@RequestMapping("/order/blind-trade-refund")
@Validated
public class AppBlindTradeRefundController {
    @Resource
    private BlindTradeRefundService blindTradeRefundService;
    @Resource
    private ActivityEnrollService enrollService;
    @Resource
    private ActivityInfoService infoService;
    @Resource
    private ActivityEnrollVerificateService verificateService;
    @Resource
    private ActivityVerificateService activityVerificateService;
    @Resource
    private ProductTypeService productTypeService;
    @Resource
    private ActivityPackageService activityPackageService;
    @Resource
    private ProductInfoService productInfoService;
    @Resource
    private DictDataService dictDataService;
    @Resource
    private GenNoCommonUtil genNoCommonUtil;

    @Resource
    private BlindMemberUserService memberUserService;

    @PostMapping("/create")
    @Operation(summary = "创建相亲订单退款")
    public CommonResult<Long> createBlindTradeRefund(@Valid @RequestBody BlindTradeRefundCreateReqVO createReqVO) {
        genNoCommonUtil.addRefundNo(createReqVO);
        return success(blindTradeRefundService.createById(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新相亲订单退款")
    public CommonResult<Boolean> updateBlindTradeRefund(@Valid @RequestBody BlindTradeRefundUpdateReqVO updateReqVO) {
        blindTradeRefundService.updateBlindTradeRefund(updateReqVO);
        return success(true);
    }

    public static <T> String parseListToStr(List<T> list) {
        String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
        return result;
    }

    @GetMapping("/get")
    @Operation(summary = "获得相亲订单退款")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<BlindTradeRefundRespVO> getBlindTradeRefund(@RequestParam("id") Long id) {
        BlindTradeRefundDO blindTradeRefund = blindTradeRefundService.getBlindTradeRefund(id);
        BlindTradeRefundRespVO vo = BlindTradeRefundConvert.INSTANCE.convert(blindTradeRefund);
        if (Objects.nonNull(vo)) {
            // 活动信息
            ActivityInfoDO activityInfoDO = infoService.getNo(vo.getActiveNo());
            if (Objects.nonNull(activityInfoDO)) {
                ActivityInfoRespVO infoRespVO = ActivityInfoConvert.INSTANCE.convert(activityInfoDO);
                //TODO 商品类型名称
                ActivityPackageExportReqVO exportReqVO = new ActivityPackageExportReqVO();
                exportReqVO.setActiveId(activityInfoDO.getId());
                List<ActivityPackageDO> activityPackageDOS = activityPackageService.getPackageList(exportReqVO);
                if (CollectionUtils.isNotEmpty(activityPackageDOS)) {
                    String str = "";
                    for (ActivityPackageDO packageRespVO : activityPackageDOS) {
                        ProductInfoDO productInfo = productInfoService.getProductInfo(packageRespVO.getProductId());
                        ProductTypeDO productTypeDO = productTypeService.getProductType(productInfo.getProductType());
                        String productType = productTypeDO.getName();
                        str += productType + ",";
                    }
                    if (StringUtils.isNotBlank(str)) {
                        infoRespVO.setProductTypeName(str.substring(0, str.lastIndexOf(",")));
                    }

                    //                    地址
                    if (CollectionUtils.isNotEmpty(activityPackageDOS)) {
                        ActivityPackageDO activityPackageDO = activityPackageDOS.stream().findFirst().orElse(null);
                        ProductInfoDO productInfo = productInfoService.getProductInfo(activityPackageDO.getProductId());
                        if (Objects.nonNull(productInfo)) {
                            infoRespVO.setAddress(productInfo.getAddress());
                        }
                    }
                    //TODO 获得已被选择参加活动人员的数量
                    // 男人
                    int activityMenNum = enrollService.getNumber(infoRespVO.getId(), (byte) 1, (byte) 0);
                    infoRespVO.setActivityMenNum(activityMenNum);
                    // 女人
                    int activityWomenNum = enrollService.getNumber(infoRespVO.getId(), (byte) 2, (byte) 0);
                    infoRespVO.setActivityWomenNum(activityWomenNum);


                    String costShareName = dictDataService.getDictData("cost_share", String.valueOf(infoRespVO.getCostShare())).getLabel();
                    infoRespVO.setCostShareName(costShareName);

//                    头像列表
                    List<ActivityEnrollDO> enrollList = enrollService.getEnrollList(new ActivityEnrollExportReqVO().setActivityId(infoRespVO.getId()).setStatus((byte) 0));
                    if (CollectionUtils.isNotEmpty(enrollList)) {
                        List<Long> collect = enrollList.stream().map(ActivityEnrollDO::getUserId).collect(Collectors.toList());
                        List<BlindMemberUserDO> memberUserList = memberUserService.getMemberUserList(collect);
                        if (CollectionUtils.isNotEmpty(memberUserList)) {
                            List<String> avatarList = memberUserList.stream().map(BlindMemberUserDO::getAvatar).collect(Collectors.toList());
                            infoRespVO.setAvatarList(avatarList);
                        }
                    }
                }
                vo.setInfoRespVO(infoRespVO);
            }
        }
        return success(vo);
    }

    @GetMapping("/list")
    @Operation(summary = "获得相亲订单退款列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    public CommonResult<List<BlindTradeRefundRespVO>> getBlindTradeRefundList(@RequestParam("ids") Collection<Long> ids) {
        List<BlindTradeRefundDO> list = blindTradeRefundService.getBlindTradeRefundList(ids);
        return success(BlindTradeRefundConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得相亲订单退款分页")
    public CommonResult<PageResult<BlindTradeRefundRespVO>> getBlindTradeRefundPage(@Valid BlindTradeRefundPageReqVO pageVO) {
        pageVO.setUserId(getLoginUserId());
        PageResult<BlindTradeRefundDO> pageResult = blindTradeRefundService.getBlindTradeRefundPage(pageVO);
        PageResult<BlindTradeRefundRespVO> page = BlindTradeRefundConvert.INSTANCE.convertPage(pageResult);
        page.getList().forEach(item -> {
            ActivityInfoDO activityInfoDO = infoService.getActivityInfo(item.getActiveNo());
            if (Objects.nonNull(activityInfoDO)) {
                item.setActiveCover(activityInfoDO.getActiveCover());
            }

        });
        return success(page);
    }


    /**
     * 关闭活动
     * 活动状态 0 未审核 1 未缴费 2.报名中 3.未开始 4.进行中 5.己结束 6.已驳回 7.已关闭
     */
    @PostMapping("/getClose")
    @Operation(summary = "关闭活动-进行退款")
    public CommonResult<Boolean> getClose(@Valid @RequestBody AppRefund appRefund) {
        ActivityInfoDO info = infoService.getInfo(appRefund.getId());
        if (Objects.isNull(info)) {
            //未找到活动时返回错误提示
            throw exception(ENROLL_NO_RELATED_ACTIVITIES_FOUND_NOT_EXISTS);
        }
        Boolean t = blindTradeRefundService.getClose(appRefund);
        return success(t);
    }

    /**
     * 取消退款
     */
    @PostMapping("/updateTradeRefund")
    @Operation(summary = "取消退款")
    @Parameter(name = "id", description = "退款id", required = true, example = "1")
    @OperateLog(type = UPDATE)
    public CommonResult<Boolean> updateTradeRefund(@RequestParam("id") Long id) {
        if (id != null && id != 0) {
            blindTradeRefundService.updateTradeRefund(id);
        }
        return success(true);
    }
}
